<template>
  <a-spin tip="正在下载二维码" :spinning="spinning">
    <div>
      <div>
        <a-button @click="goBack">返回</a-button>
      </div>
      <div class="title">
        <div style="color: black; font-size: 20px">全校各班二维码</div>
        <div style="font-size: 12px; margin-top: 12px">
          攻略: 如何妙用班级二维码?
          <span style="color: #ff4d4f !important;; cursor: pointer" @click="clickView">点此查看</span>
        </div>
      </div>
      <div
        style="color: #ff4d4f !important;; position: absolute; right: 10px; cursor: pointer"
        @click="donloadQrcode()"
      >
        <a-icon type="download" />打包下载全校二维码
      </div>
      <div style="margin-top: 40px;height: 200px;">
        <a-table :columns="columns" :data-source="data" bordered >
          <template slot="cz" slot-scope="text, record">
            <span style="color: #ff4d4f !important;; cursor: pointer" @click="view(record)"
              >预览</span
            >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span
              style="color: #ff4d4f !important;; cursor: pointer"
              @click="download(record)"
              >下载二维码</span
            >
          </template>
          <template slot="money" slot-scope="text, record">
            <vue-qr :id="'qr' + record.key" :text="record.name" style="width: 100px; height: 100px;"></vue-qr>
          </template>
        </a-table>
        <div
          class="qrcode"
          id="qrcode"
          style="display: none"
          ref="qrCodeUrl"
        ></div>
        <a-modal
          v-model="visible"
          centered
          :title="title"
          :footer="null"
          width="400px"
        >
          <div
            class="qrcode"
            id="qrcode"
            style="margin-left: 80px"
            ref="qrCodeUrl"
          ></div>
          <div
            style="
              text-align: center;
              justify-content: center;
              align-content: center;
            "
          >
            <a-button
              type="primary"
              @click="downloadClick"
              style="margin-top: 20px"
            >
              下载二维码
            </a-button>
          </div>
        </a-modal>
      </div>
     
    </div>
  </a-spin>
</template>

<script>
const columns = [
  {
    title: "班级",
    dataIndex: "name",
  },
  {
    title: "班主任",
    className: "column-money",
    dataIndex: "money",
    width: "400px",
  },
  {
    title: "二维码",
    dataIndex: "money",
    scopedSlots: { customRender: "money" },
    width: "80px",
    height:"80px"
  },
  {
    title: "下载尺寸为A4纸大小: 210mmx297mm",
    dataIndex: "cz",
    scopedSlots: { customRender: "cz" },
  },
];
const data = [
  {
    key: 1,
    name: "高中教育-一年级",
    money: "",
    address: "",
  },
  {
    key: 2,
    name: "初中教育-初一二班",
    money: "",
    address: "",
  },
  {
    key: 3,
    name: "其他教育-教师进修-一年级-初一-班",
    money: "",
    address: "",
  },
];
import QRCode from "qrcodejs2";
import JSZip from "jszip";
import html2canvas from "html2canvas";
import saveAs from "file-saver";
import VueQr from "vue-qr";
export default {
  name: "Demo",
  components: { VueQr },
  data() {
    return {
      data,
      columns,
      visible: false,
      title: "",
      spinning: false,
    };
  },
  methods: {
    goBack() {
      this.$router.back();
    },
    clickView(){
        window.open("https://page.dingtalk.com/wow/dingtalk/act/classqrcode?wh_biz=tm")
    },
    donloadQrcode() {
      var zip = new JSZip();
      var CodeDase64 = zip.folder("全校二维码"); //包名称

      this.spinning = true;
      data.forEach((e, index) => {
        this.$nextTick(() => {
          this.htmls(e, index, zip, CodeDase64);
        });
      });
    },
    htmls(row, index, zip, CodeDase64) {
      var htmlName = document.getElementById("qr" + row.key);
      setTimeout(() => {
        html2canvas(htmlName).then((resolve) => {
          let imgUrl = resolve.toDataURL("image/png"); //此时就得到了dom元素转成了base64的图片
          const basePic = imgUrl.replace(/^data:image\/(png|jpg);base64,/, "");
          CodeDase64.file(row.name + ".png", basePic, {
            base64: true,
          });
          if (data.length - 1 == index) {
            this.spinning = false;
            zip
              .generateAsync({ type: "blob" }) // zip下载
              .then((content) => {
                saveAs(content, "全校二维码.zip"); // zip下载后的名字
              });
          }
        });
      }, 500);
    },

    async download(val) {
      this.title = val.name;
      await this.creatQrCode();
      await this.downloadClick();
    },
    creatQrCode() {
      this.$refs.qrCodeUrl.innerHTML = "";
      new QRCode(this.$refs.qrCodeUrl, {
        text: "我是" + this.title, // 需要转换为二维码的内容
        width: 200,
        height: 200,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });
    },
    view(val) {
      var that = this;
      this.visible = true;
      this.title = val.name;
      setTimeout(function () {
        that.creatQrCode();
      }, 100);
    },
    // 下载二维码
    downloadClick() {
      // 先找到canvas节点下的二维码图片
      const myCanvas = document
        .getElementById("qrcode")
        .getElementsByTagName("canvas");
      const img = document.getElementById("qrcode").getElementsByTagName("img");
      // 创建一个a节点
      const a = document.createElement("a");
      // 设置a的href属性将canvas变成png格式
      const imgURL = myCanvas[0].toDataURL("image/jpg");
      const ua = navigator.userAgent;
      if (ua.indexOf("Trident") !== -1 && ua.indexOf("Windows") !== -1) {
        // IE内核 并且  windows系统 情况下 才执行;
        var bstr = atob(imgURL.split(",")[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        const blob = new Blob([u8arr]);
        window.navigator.msSaveOrOpenBlob(blob, "下载" + "." + "png");
      } else if (ua.indexOf("Firefox") > -1) {
        // 火狐兼容下载
        const blob = this.base64ToBlob(imgURL); //new Blob([content]);
        const evt = document.createEvent("HTMLEvents");
        evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        a.download = " "; //下载图片名称，如果填内容识别不到，下载为未知文件，所以我这里就不填为空
        a.href = URL.createObjectURL(blob);
        a.dispatchEvent(
          new MouseEvent("click", {
            bubbles: true,
            cancelable: true,
            view: window,
          })
        );
      } else {
        // 谷歌兼容下载
        img.src = myCanvas[0].toDataURL("image/jpg");
        a.href = img.src;
        // 设置下载文件的名字
        a.download = this.title + "二维码";
        // 点击
        a.click();

        this.$message({
          message: "下载成功，已保存到桌面",
          type: "success",
        });
      }
    },
    // base64转blob
    base64ToBlob(code) {
      let parts = code.split(";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], {
        type: contentType,
      });
    },
  },
};
</script>

<style scoped>
.title {
  text-align: center;
  justify-content: center;
  align-content: center;
}
.ant-table-thead > tr > th{
    color:rgba(0, 0, 0, 0.5) !important;
}
</style>
